package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.CreateNotification;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class AddComment
 */
public class AddComment extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddComment() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * Adds comment to a story which is made by a registered user. If the comment is successfully posted, then the owner
	 * of the story is sent a notification. 
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		String f_requestType = request.getParameter("request_type");
		String username;
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
			username = (String)request.getSession().getAttribute("username");
			// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.
		}
		else{
			username = request.getParameter("username");
		}
		
		if(username == null){
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
			return;
		}

		int f_storyId = Integer.parseInt(request.getParameter("story_id"));
		
		String f_commentBody = request.getParameter("comment_body");
		PreparedStatement stmt = null;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				CreateNotification newNotificaiton = new CreateNotification();
				request.setCharacterEncoding("utf8");
				response.setContentType("application/json");
				java.util.Date today = new java.util.Date();
				int f_userId = Utilities.getUserId(conn, username);
				//Timestamp is also added to the database with the comment in order to display comments in a chronological order
				Timestamp f_timeStamp = new Timestamp(today.getTime());
				stmt = conn.prepareStatement("INSERT INTO "
						+ TableNames.COMMENTS_TABLE
						+ "(u_id,s_id,date,body) VALUES (?,?,?,?)");

				stmt.setInt(1, f_userId);
				stmt.setInt(2, f_storyId);
				stmt.setTimestamp(3, f_timeStamp);
				stmt.setString(4, f_commentBody);

				int databaseResponse = stmt.executeUpdate();

				boolean commentSuccess = false; // as default
				/*
				 * If the comment is added to the story successfully, a notification for the owner of the story is created.
				 * Please refer to CreateNotification.java in utils package to get a more detailed description of the notification
				 * system.
				 */
				if (databaseResponse == 1) {
					commentSuccess = true;
					newNotificaiton.createCommentNotification(f_userId,	f_storyId);
				} else if (databaseResponse == 0) {
					commentSuccess = false;
				} else {
					//DO NOTHING
				}
				
				/*
				 * Based on the source of the request (Web or Android client) different responses are created.
				 * Android clients are returned a JSONObject while Web clients are returned a HTTPServletResponse
				 * object.
				 */
				if (f_requestType.equals("Android")) {
					JSONObject commentResultJsonObject = new JSONObject();
					try {
						commentResultJsonObject.put("addCommentSuccess", commentSuccess);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(commentResultJsonObject.toString());
				} else if (f_requestType.equals("Web")) {
					// After adding the comment, redirect the user to the story page
					request.setAttribute("addCommentSuccess", commentSuccess);
					response.sendRedirect("ReadStory?story_id=" + f_storyId
							+ "&request_type=Web");
				} else {
					//DO NOTHING
				}

			} catch (SQLException e) {
				out.print(e.getMessage());
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
